package com.zheng.upms.rpc.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.zheng.common.annotation.BaseService;
import com.zheng.common.base.BaseServiceImpl;
import com.zheng.common.util.MD5Util;
import com.zheng.common.util.PropertiesFileUtil;
import com.zheng.upms.dao.mapper.UpmsUserMapper;
import com.zheng.upms.dao.model.UpmsUser;
import com.zheng.upms.rpc.api.UpmsUserRoleService;
import com.zheng.upms.rpc.api.UpmsUserService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.UUID;

/**
 * <p>
 * 用户 服务实现类
 * </p>
 *
 * @author likun
 * @since 2017-12-29
 */
@Service
@Transactional
@BaseService
public class UpmsUserServiceImpl extends BaseServiceImpl<UpmsUserMapper, UpmsUser> implements UpmsUserService {
    private static Logger _log = LoggerFactory.getLogger(UpmsUserServiceImpl.class);

    @Autowired
    UpmsUserRoleService upmsUserRoleService;

    @Override
    public UpmsUser createUser(UpmsUser upmsUser) {
        long count = super.selectCount(new EntityWrapper<UpmsUser>().eq("username", upmsUser.getUsername()));
        if (count > 0) {
            return null;
        }
        //用户密码
        String password ;
        if(StringUtils.isBlank(upmsUser.getPassword())){
            password = PropertiesFileUtil.getInstance().get("defaultPassword");
        }else {
            password = upmsUser.getPassword();
        }

        String salt = UUID.randomUUID().toString().replaceAll("-", "");
        upmsUser.setSalt(salt);
        upmsUser.setPassword(MD5Util.MD5(password + upmsUser.getSalt()));
        upmsUser.setCtime(new Date());
        super.baseMapper.insert(upmsUser);

        //设置用户角色
        String defaultRoleStr = PropertiesFileUtil.getInstance().get("defaultRoleIds");
        String[] roleIds = defaultRoleStr.split(",");

        upmsUserRoleService.role(roleIds, upmsUser.getUserId());

        return upmsUser;
    }

    /**
     * 密码重置
     * @param id
     * @return
     */
    @Override
    public String resetPassword(int id) {
        UpmsUser upmsUser = new UpmsUser();
        upmsUser.setUserId(id);

        String password = PropertiesFileUtil.getInstance().get("defaultPassword");
        String salt = UUID.randomUUID().toString().replaceAll("-", "");
        upmsUser.setSalt(salt);
        upmsUser.setPassword(MD5Util.MD5(password + salt));

        if(super.updateById(upmsUser)){
            return password;
        }else {
            return null;
        }
    }
}
